// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
#include "pch.h"
#include "ThumbnailManager.h"

using namespace Weathr;

using namespace concurrency;
using namespace Platform;
using namespace Windows::Storage;
using namespace Windows::Storage::Streams;

String^ ThumbnailFolder = R"(Thumbnails\)";
const GUID ThumbnailImageFormat = GUID_ContainerFormatJpeg;

String^ GetThumbnailName(Forecast^ forecast)
{
    return String::Concat(forecast->UniqueIdentifier, ".jpg");
}

String^ GetImagePath(Forecast^ forecast)
{
    return String::Concat(ThumbnailFolder, GetThumbnailName(forecast));
}

GUID ThumbnailManager::GetThumbnailImageFormat()
{
    return ThumbnailImageFormat;
}

task<StorageFile^> ThumbnailManager::GetThumbnailAsync(Forecast^ forecast)
{
    auto fileName = GetImagePath(forecast);
    return create_task(ApplicationData::Current->LocalFolder->GetFileAsync(fileName)).then([](task<StorageFile^> previousTask)
    {
        try
        {
            return previousTask.get();
        }
        catch (COMException^ e)
        {
            // File does not exist.
            return static_cast<StorageFile^>(nullptr);
        }
    });
}

task<StorageFile^> ThumbnailManager::CreateThumbnailAsync(Forecast^ forecast)
{
    auto fileName = GetImagePath(forecast);
    return create_task(ApplicationData::Current->LocalFolder->CreateFileAsync(fileName, CreationCollisionOption::ReplaceExisting));
}

task<void> ThumbnailManager::WriteThumbnailAsync(Forecast^ forecast, IRandomAccessStream^ thumbnailStream)
{
    return create_task(thumbnailStream->FlushAsync()).then([forecast, thumbnailStream](bool)
    {
        // This ensures that the file is closed.
        delete thumbnailStream;

        return GetThumbnailAsync(forecast).then([forecast](StorageFile^ file)
        {
            if (file != nullptr) // forecast may have been deleted
            {
                run_async_non_interactive([forecast, file]()
                {
                    forecast->ThumbnailImagePath = file->Path;
                });
            }
        });
    });
}
